import requests
from bs4 import BeautifulSoup as bs
from lxml import etree
from Work import Work
from Logger import *


class User:
    def __init__(self, token, owernId):
        self.token = token
        self.owernId = owernId

    # 发起请求，为别的函数服务。
    @staticmethod
    def post(url, headers, data):
        res = requests.post(url, headers=headers, data=data.encode('utf-8'))
        # 利用BS对返回的原始文本进行格式化。
        return bs(res.text, 'html.parser').get_text()

    # 处理工单。
    def do(self):
        works = self.getWorks()
        for work in works:
            rule = work.getRule()
            if not rule.isNone():
                logging.info('工单匹配成功。{}, {}.'.format(work, rule.pattern))
                # 按道理来说，只要匹配上，就应该受理。
                if work.isWarnCleard():
                    # 告警消除。
                    if not work.isDealt():
                        # 工单未受理，受理工单。工单有可能通过别的方式受理了，受理之后，不需要再受理。
                        self.deal(work)
                    self.atStation(work)
                    self.reply(work, rule)

    # 获取工单列表。
    def getWorks(self):
        data = '<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /><v:Body><n0:selectNowWOrkForInit id="o0" c:root="1" xmlns:n0="http://webservice.eoms.inspur.com/PhoneInterFaceClass"><token i:type="d:string">{}</token><startTime i:type="d:string">2018-01-01 01:01:00</startTime><endTime i:type="d:string">2018-12-12 23:29:00</endTime><owernId i:type="d:string">{}</owernId><startPage i:type="d:int">1</startPage><pageNum i:type="d:int">256</pageNum></n0:selectNowWOrkForInit></v:Body></v:Envelope>'
        data = data.format(self.token, self.owernId)  # 格式化token和owernId
        url = 'http://211.137.182.254:9372/eoms3/services/PhoneInterFaceClassNew'
        headers = {
            'User-Agent': 'ksoap2-android/2.6.0+',
            'SOAPAction': 'http://webservice.eoms.inspur.com/PhoneInterFaceClassselectNowWOrkForInit'
        }
        res = User.post(url, headers, data)
        et = etree.XML(res)  # 利用bs来格解码html entity编码。

        totleNum = et.xpath('recordInfo//fieldEnName[text()="totleNum"]/following-sibling::fieldContent[1]')[0].text
        logging.info('工单共：{}条。'.format(totleNum))

        formNos = et.xpath('recordInfo//fieldEnName[text()="formNo"]/following-sibling::fieldContent[1]')
        titles = et.xpath('recordInfo//fieldEnName[text()="title"]/following-sibling::fieldContent[1]')
        piids = et.xpath('recordInfo//fieldEnName[text()="piid"]/following-sibling::fieldContent[1]')
        tkiids = et.xpath('recordInfo//fieldEnName[text()="tkiid"]/following-sibling::fieldContent[1]')
        isWarnClears = et.xpath('recordInfo//fieldEnName[text()="isWarnClear"]/following-sibling::fieldContent[1]')
        states = et.xpath('recordInfo//fieldEnName[text()="state"]/following-sibling::fieldContent[1]')
        classOneNames = et.xpath('recordInfo//fieldEnName[text()="classOneName"]/following-sibling::fieldContent[1]')

        works = []
        # 获取故障工单。
        for formNo, title, piid, tkiid, isWarnClear, state, classOneName in zip(formNos, titles, piids, tkiids,
                                                                                isWarnClears, states, classOneNames):
            tmp = Work(formNo.text, title.text, piid.text, tkiid.text, isWarnClear.text, state.text, classOneName.text)
            logging.info(tmp)
            works.append(tmp)
        return works

    # 受理工单。
    def deal(self, work):
        data = '<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /><v:Body><n0:dealPcWorkForNew id="o0" c:root="1" xmlns:n0="http://webservice.eoms.inspur.com/PhoneInterFaceClass"><token i:type="d:string">{}</token><piid i:type="d:string">{}</piid><tkiid i:type="d:string">{}</tkiid><ownerName i:type="d:string"></ownerName><companyName i:type="d:string">东营</companyName><userId i:type="d:string">{}</userId><model i:type="d:string">0</model><faultReasonType i:type="d:string"></faultReasonType><faultReasonDetail i:type="d:string"></faultReasonDetail><fualtReason i:type="d:string"></fualtReason><dealMeas i:type="d:string"></dealMeas><isAtStation i:type="d:string"></isAtStation><userNowLongitude i:type="d:string"></userNowLongitude><userNameLatitude i:type="d:string"></userNameLatitude><longitude i:type="d:string"></longitude><latitude i:type="d:string"></latitude><checkResult i:type="d:string"></checkResult><isDealEffeReason i:type="d:string"></isDealEffeReason><morePhoneParams i:type="d:string">867085037390500</morePhoneParams><slReason i:type="d:string"></slReason><isSlDadian i:type="d:string"></isSlDadian><stageReason i:type="d:string"></stageReason><isTuifu i:type="d:string">N</isTuifu></n0:dealPcWorkForNew></v:Body></v:Envelope>'
        data = data.format(self.token, work.piid, work.tkiid, self.owernId)
        url = 'http://211.137.182.254:9372/eoms3/services/PhoneInterFaceClassNew'
        headers = {
            'User-Agent': 'ksoap2-android/2.6.0+',
            'SOAPAction': 'http://webservice.eoms.inspur.com/PhoneInterFaceClassdealPcWorkForNew'
        }

        res = User.post(url, headers, data)
        # print(res)
        et = etree.XML(res)
        # 受理的结果。
        result = et.xpath('result')[0].text
        tmp = '受理工单：{}, 结果：{}。'.format(work, result)
        logging.info(tmp)
        return result == '0'

    # 打点。
    def atStation(self, work):
        data = '<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /><v:Body><n0:dealPhoneAtStation id="o0" c:root="1" xmlns:n0="http://webservice.eoms.inspur.com/PhoneInterFaceClass"><userid i:type="d:string">{}</userid><token i:type="d:string">{}</token><piid i:type="d:string">{}</piid><tkiid i:type="d:string">{}</tkiid><isAtStation i:type="d:string">否</isAtStation><userNowLongitude i:type="d:string"></userNowLongitude><userNameLatitude i:type="d:string"></userNameLatitude><longitude i:type="d:string"></longitude><latitude i:type="d:string"></latitude><checkResult i:type="d:string"></checkResult><morePhoneParams i:type="d:string"></morePhoneParams><typeModuleStr i:type="d:string"></typeModuleStr><reasonDetailStr i:type="d:string"></reasonDetailStr><class_one_name i:type="d:string">{}</class_one_name><class_two_name i:type="d:string">{}</class_two_name></n0:dealPhoneAtStation></v:Body></v:Envelope>'
        data = data.format(self.owernId, self.token, work.piid, work.tkiid, work.classOneName, work.classTwoName)
        url = 'http://211.137.182.254:9372/eoms3/services/PhoneInterFaceClassNew'
        headers = {
            'User-Agent': 'ksoap2-android/2.6.0+',
            'SOAPAction': 'http://webservice.eoms.inspur.com/PhoneInterFaceClassdealPhoneAtStation'
        }

        res = User.post(url, headers, data)
        # print(res)
        et = etree.XML(res)
        # 打点的结果。
        result = et.xpath('result')[0].text
        tmp = '打点：{}, 结果：{}。'.format(work, result)
        logging.info(tmp)
        return result == '0'

    # 回复工单。
    def reply(self, work, rule):
        data = '<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /><v:Body><n0:dealPcWorkForNew id="o0" c:root="1" xmlns:n0="http://webservice.eoms.inspur.com/PhoneInterFaceClass"><token i:type="d:string">{}</token><piid i:type="d:string">{}</piid><tkiid i:type="d:string">{}</tkiid><ownerName i:type="d:string"></ownerName><companyName i:type="d:string">东营</companyName><userId i:type="d:string">{}</userId><model i:type="d:string">1</model><faultReasonType i:type="d:string">{}</faultReasonType><faultReasonDetail i:type="d:string">{}</faultReasonDetail><fualtReason i:type="d:string">{}</fualtReason><dealMeas i:type="d:string">{}</dealMeas><isAtStation i:type="d:string"></isAtStation><userNowLongitude i:type="d:string"></userNowLongitude><userNameLatitude i:type="d:string"></userNameLatitude><longitude i:type="d:string"></longitude><latitude i:type="d:string"></latitude><checkResult i:type="d:string"></checkResult><isDealEffeReason i:type="d:string"></isDealEffeReason><morePhoneParams i:type="d:string">867085037390500;y</morePhoneParams><slReason i:type="d:string"></slReason><isSlDadian i:type="d:string"></isSlDadian><stageReason i:type="d:string"></stageReason><isImpactbusiness i:type="d:string">否</isImpactbusiness><businComebacktime i:type="d:string"></businComebacktime><isTuifu i:type="d:string">N</isTuifu></n0:dealPcWorkForNew></v:Body></v:Envelope>'
        # 通过work.title查询Rule，取得回复工单的数据。
        data = data.format(self.token, work.piid, work.tkiid, self.owernId,
                           rule.faultReasonType, rule.faultReasonDetail, rule.fualtReason, rule.dealMeas)
        url = 'http://211.137.182.254:9372/eoms3/services/PhoneInterFaceClassNew'
        headers = {
            'User-Agent': 'ksoap2-android/2.6.0+',
            'SOAPAction': 'http://webservice.eoms.inspur.com/PhoneInterFaceClassdealPcWorkForNew'
        }

        res = User.post(url, headers, data)
        # print(res)
        et = etree.XML(res)
        # 打点的结果。
        result = et.xpath('result')[0].text
        tmp = '回复工单：{}, 匹配：{}, 结果：{}。'.format(work, rule, result)
        logging.info(tmp)
        return result == '0'
